﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API.Core.MediaTypeFormatter
{
    public class CommerceMLFormatter : System.Net.Http.Formatting.BufferedMediaTypeFormatter
    {
        public CommerceMLFormatter()
        {
            this.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/commerceML"));
        }

        public override bool CanReadType(Type type)
        {
            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return true;

            //if (type == typeof(IQueryable<Models.WH_INVOICE>))
            //    return true;

            //return false;
        }

        public override void WriteToStream(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content)
        {
            var data = new CommerceML.Version205.КоммерческаяИнформация();

            if (value is IEnumerable<Models.V_IncomingInvoices>)
            {
                data = new Core.CommerceMLConverter().Convert((value as IEnumerable<Models.V_IncomingInvoices>).ToList());
            }

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommerceML.Version205.КоммерческаяИнформация));
            serializer.Serialize(writeStream, data);
        }

        public override object ReadFromStream(Type type, System.IO.Stream readStream, System.Net.Http.HttpContent content, System.Net.Http.Formatting.IFormatterLogger formatterLogger)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommerceML.Version205.КоммерческаяИнформация));
            var commerceML = serializer.Deserialize(readStream);
            var data = new Core.CommerceMLConverter().Convert(commerceML as CommerceML.Version205.КоммерческаяИнформация);

            return data;
        }
    }

}